import React,{ useEffect } from 'react';
import get from 'lodash/get';
import { storage_keys } from '../../constants/storage';
import { routers } from '@/router';
import HttpConfig from '@/constants/http.config';
import { ContainerEntity } from '@/models/container_entity';
import { Store } from '@/store/core.store';
import UserStore,{ InterfaceGitlabToken,InterfaceGitlabUser, InterfaceUser } from '@/store/user.store';
import Taro from '@tarojs/taro';
import { cookies } from '@/utils/cookie';
import { TaroFetch } from '@/utils/fetch';
import { View } from '@tarojs/components';
import { getGitlabRedirectUri } from '@/constants/gitlab';
const baseCls = `legions-login-success`;
const _fetch = new TaroFetch();
function getQueryVariable(variable: string) {
    const query = location.search.substring(1)
    const params = query.split('&');
    if (params.length) {
        for (let i = 0; i < params.length; i++) {
            let pair = params[i].split('=');
            if (pair[0] === variable) { return pair[1]; }
        }
    }
    return ''
}
/** 登录成功 */
export default function LoginSuccess(){
    const store = Store.getStore(UserStore)
    useEffect(() => {
        document.title = 'gitlab授权中....'
        Taro.showLoading({
            title: '授权登录中...'
        })
        const code = getQueryVariable('code');
        const state = getQueryVariable('state'); // 来源(weapp,h5)  譬如从微信小程序使用发起授权以及在H5移动应用使用发起授权
        if (code) {
            let redirect_uri = getGitlabRedirectUri()
            _fetch.request({
                url: `${HttpConfig.api}/gitlab/mobile/authorization/login`,
                data: {
                    code,
                    redirect_uri,
                },
                method:'GET',
                // mode: 'no-cors',
            }).then((result) => {
                const data = result.data as InstanceType<typeof ContainerEntity>
                Taro.hideLoading()
                if (data?.success) {
                    const oauth_token = get(data.data,'gitlab_token') as unknown as InterfaceGitlabToken
                    const gitlab_user = get(data.data,'gitlab_user') as unknown as InterfaceGitlabUser
                    const admin_user = get(data.data,'admin_user')as unknown as InterfaceUser
                    if (get(gitlab_user,'username') && get(oauth_token,'access_token') && get(admin_user,'name')) {
                        if (Taro.getEnv() === Taro.ENV_TYPE.WEB) {
                            store.setOauthToken(oauth_token);
                            store.setGitlabUser(gitlab_user);
                            store.setUser(admin_user);
                            const gitlab_token_json = JSON.stringify(oauth_token);
                            const gitlab_user_json = JSON.stringify(gitlab_user);
                            if (state === 'h5') {
                                const token = get(admin_user,'token') as unknown as string;
                                const expiresTime = get(admin_user,'expiresTime') as unknown as number;
                                cookies.set(storage_keys.admin_bearer,token,expiresTime);
                                Taro.setStorageSync(storage_keys.gitlab_token,oauth_token);
                                Taro.setStorageSync(storage_keys.gitlab_user,gitlab_user);
                                Taro.setStorageSync(storage_keys.admin_user,admin_user);
                                Taro.navigateTo({
                                    url:routers.home
                                })
                            }
                            if (state === 'weapp') {
                                window.wx.miniProgram.navigateTo({ url: `${routers.home}?gitlab_token=${gitlab_token_json}&gitlab_user=${gitlab_user_json}&admin_user=${JSON.stringify(admin_user)}` })
                            }
                        }
                    }
                }
            })
        }
    },[])
    return <View className={baseCls}>
    </View>
}